package com.wyw.learning.thread.flowcontrol.countdownlatch;

import java.util.concurrent.*;

/**
 * 工厂中，质检，5个工人检查，所有人都认为通过，才通过
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class CountDownLatchDemo1 {

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(5);
//        ExecutorService service = Executors.newFixedThreadPool(5);
        ExecutorService service = new ThreadPoolExecutor(5, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        for(int i = 0; i<5; i++) {
            final int no = i + 1;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep((long) (Math.random()*10000));
                        System.out.println("No." + no + "完成了检查");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        latch.countDown();//这里一旦发生异常也会出现减一操作哦，如果异常不想减一，不要放在这里
                    }
                }
            };
            service.submit(runnable);
        }
        System.out.println("等待5个人检查完.....");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("所有人都完成了工作，进入下一个环节。");
//        service.shutdown();
    }
}
